import { defineConfig, loadEnv } from 'vite'

const path = require('path')
import vue from '@vitejs/plugin-vue'
import VitePluginElementPlus from 'vite-plugin-element-plus'
import legacy from '@vitejs/plugin-legacy'
import { viteMockServe } from 'vite-plugin-mock'
import { setting } from './src/config/setting'
import AutoImport from 'unplugin-auto-import/vite'
import Components from 'unplugin-vue-components/vite'

import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import { svgBuilder } from './src/plugins/icon/svgBuilder'

// import viteSvgIcons from 'vite-plugin-svg-icons'

function resolve(dir) {
  return path.join(__dirname, '.', dir)
}

const {
  base,
  publicDir,
  assetsDir,
  sourcemap,
  cssCodeSplit,
  brotliSize,
  strictPort,
  open,
  logLevel,
  clearScreen,
  drop_debugger,
  drop_console,
  chunkSizeWarningLimit
} = setting

export default ({ mode }) => {
  const isDev = mode === 'development'
  const envConfig = loadEnv(mode, process.cwd())
  const originPlugins = [
    vue(),
    legacy({
      polyfills: ['es.promise.finally', 'es/set'],
      modernPolyfills: ['es.promise.finally']
    })
  ]

  let configPlugins = []
  if (isDev) {
    configPlugins = [
      VitePluginElementPlus({
        // 如果你需要使用 [component name].scss 源文件，你需要把下面的注释取消掉。
        // 对于所有的 API 你可以参考 https://github.com/element-plus/vite-plugin-element-plus
        // 的文档注释
        // useSource: true,
        format: isDev ? 'esm' : 'cjs'
      }),
      Components({
        resolvers: [
          ElementPlusResolver({
            importStyle: 'sass'
          })
        ]
      })
    ]
  } else {
    configPlugins = [
      AutoImport({
        resolvers: [ElementPlusResolver()]
      }),
      Components({
        resolvers: [ElementPlusResolver()]
      })
    ]
  }
  const plugins = [
    ...originPlugins,
    ...configPlugins,
    // viteSvgIcons({
    //   iconDirs: [
    //     path.resolve(__dirname, 'src/icons/svg')
    //   ],
    //   symbolId: 'icon-[dir]-[name]'
    // })
    viteMockServe({
      mockPath: 'mock',
      supportTs: false,
      localEnabled: isDev,
      prodEnabled: !isDev,
      injectCode: `
          import { setupProdMockServer } from './mockProdServer';
          setupProdMockServer();
        `
    }),
    svgBuilder('./src/icons/svg/')
  ]
  return defineConfig({
    root: process.cwd(),
    base,
    publicDir,
    logLevel,
    clearScreen,
    resolve: {
      extensions: ['.js', '.jsx', '.json', '.vue'],
      alias: {
        '@': resolve('src'),
        styles: path.resolve(__dirname, 'src/styles'),
        views: path.resolve(__dirname, 'src/views'),
        utils: path.resolve(__dirname, 'src/utils')
      }
    },
    // css: {
    //   preprocessorOptions: {
    //     // 引入公用的样式
    //     scss: {
    //       additionalData: `@use "@/styles/index.scss" as *;`
    //     }
    //   }
    // },
    corePlugins: {
      preflight: false
    },
    server: {
      host: envConfig.VITE_BASE_URL,
      port: envConfig.VITE_PORT,
      cors: true,
      open,
      strictPort,
      fs: {
        strict: false
      }
    },
    plugins,
    build: {
      outDir: envConfig.VITE_OUTPUT_DIR,
      assetsDir,
      sourcemap,
      cssCodeSplit,
      brotliSize,
      minify: 'terser',
      terserOptions: {
        compress: {
          keep_infinity: true,
          drop_debugger,
          drop_console
        }
      },
      chunkSizeWarningLimit
    },
    optimizeDeps: {
      // 检测需要预构建的依赖项
      entries: []
    },
    define: {
      process: {
        cwd: function() {
          return process.cwd()
        }
      }
    }
  })
}
